// pages/login/login.js
const app = getApp()
const util = require('../../utils/util.js')

Page({
  data: {
    code: null,
    getUserInfoRes: null,
    userInfo: null,
    hasLogedIn: false
  },
  /* login  */
  shopLogin: function() {
    return new Promise((resolve, reject) =>{
      let code = this.data.code;
      let getUserInfoRes = this.data.getUserInfoRes;
      util.myRequest({
        url: "https://nideshop.bluej.cn/" + "auth/loginByWeixin",
        method: 'post',
        data: {
          appId: 'wx4578fa0b74198240',
          secret:'67467bf07f0019ccf76a3c017e5989a7',
          code: code,
          userInfo: getUserInfoRes
        },
        success: function(res) {
          if(!!res.data){
            resolve(res.data.token);
          } else{
            reject('err')
            /* 服务器错误 */
            wx.redirectTo({
              url: '/pages/toolsPage/page404/page404'
            })
          }
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
  },
  wxLogin: function() {
    return new Promise((resolve, reject) =>{
      wx.login({
        success: res =>{
          resolve(res.code)
        },
        fail: err =>{
          reject(err)
        }
      })
    })
  },
  /**
   * dataSave Part
   *  1. code
   *  2. userInfo getUserInfoRes
   *  3. token (in storage)//
  */
  saveCode: function(code) {
    this.setData({
      code: code
    })
  },
  saveToken: function(token) {
    app.globalData.token = token;
    wx.setStorage({
      key:"token",
      data:token,
    });
  },

  /* test */
  returnLatestPage: function() {
    let ui = this.data.userInfo;
    wx.setStorage({
      key:"userInfo",
      data:ui,
    });
    wx.showToast({
      title: "登录成功"
    });
    let timer = setTimeout(() => {
      console.log('time out');
      wx.navigateBack({
        delta: 1
      })      
      clearTimeout(timer);
      timer = null;
    }, 2000);
  },
  /* bind button & get res */
  getUserInfo: function(e) {
    if (!!e.detail.userInfo) {
      /* 用户同意微信授权 */
      this.setData({
        getUserInfoRes: e.detail,
        userInfo: e.detail.userInfo
      })
      this.shopLogin()
        .then(this.saveToken)
        .then( this.returnLatestPage ).catch(err =>{console.log(err)})
    } else {
      /* 用户拒绝微信授权 */
      console.log("授权被拒绝")
      wx.showToast({
        title: "请授权",
        image: "../../static/images/auth.png"
      })
    }
  },
  /* reuurn to index */
  toIndex: function() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.wxLogin().then( this.saveCode )
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})